package com.tehui.activity.impl;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.model.TradeResult;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;
import com.tehui.R;
import com.tehui.activity.BaseActivity;
import com.tehui.activity.LoginActivity;
import com.tehui.adapter.HomeAdapter;
import com.tehui.bean.BrandData;
import com.tehui.bean.DanData;
import com.tehui.global.Global;
import com.tehui.utils.tools.PrefUtils;
import com.tehui.utils.ui.UiUtils;
import com.tehui.utils.web.MyCallback;
import com.tehui.utils.web.NR;
import com.tehui.utils.web.ShareUtil;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.tehui.app.MyApplication.IS_TAOKE;

public class CommodityActivity extends BaseActivity {

    @BindView(R.id.ivShare)
    ImageView    ivShare;
    @BindView(R.id.invalid)
    LinearLayout invalid;
    @BindView(R.id.rl)
    RecyclerView rl;
    @BindView(R.id.llBtn)
    LinearLayout llBtn;
    @BindView(R.id.btnNet)
    Button       btnNet;
    @BindView(R.id.llNet)
    LinearLayout llNet;
    @BindView(R.id.ivFavorite)
    ImageView    ivFavorite;
    @BindView(R.id.pro)
    LinearLayout pro;
    @BindView(R.id.goHome)
    Button       goHome;

    private Map<String, String>        exParams;
    private AlibcShowParams            alibcShowParams;//页面打开方式，默认，H5，Native
    private String                     goodsId;
    private String                     text;
    private String                     picUrl;
    private boolean                    isChoice;
    private String                     quanNum;
    private String                     saleNum;
    private String                     priceNum;
    private String                     orgPrice;
    private String                     price;
    private String                     substring;
    private String                     cid;
    private List<BrandData.ResultBean> result;
    private String                     sendFavorite;
    private String                     openId;
    private AlibcPage                  alibcPage;
    private String                     isTmall;
    private String                     commission;
    private boolean                    isLoging;
    private String                     pid;
    private Bitmap                     mBitmap;
    private PopupWindow                popupWindow;
    private String                     quanid;
    private String                     taoWord;
    private String                     taokeId;
    private String                     shortLink;
    private View                       headerView;
    private ImageView                  pic;
    private TextView                   tvText;
    private TextView                   tvMoney;
    private TextView                   oldMoney;
    private TextView                   sellNumber;
    private TextView                   youh;
    private TextView                   quan;
    private TextView                   tvQuan;
    private TextView                   tvBao;
    private TextView                   tvTime;
    private String downLink = "http://dl.21tehui.com/AppUpdate/TGpageAppDown.html";


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_commodity;
    }

    @Override
    public void initViewListener() {
        super.initViewListener();
        ivShare.setClickable(false);
        goHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToActivity(HomeActivity.class);
            }
        });

        btnNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pro.setVisibility(View.VISIBLE);
                llNet.setVisibility(View.GONE);
                if (initNetError()) {
                    initDatas();
                }
            }
        });

        alibcPage = new AlibcPage("http://shop.m.taobao.com/shop/coupon.htm?seller_id=2036155597&activity_id=3ad63813e54e4cc6b2b01253d97ba9b2");
    }

    @Override
    public void initActivityData() {
        super.initActivityData();
        headerView = View.inflate(this, R.layout.comm_header_layout, null);
        taokeId = getString(R.string.taokeId);
        ivShare.setVisibility(View.VISIBLE);
        pid = getString(R.string.pid);
        openId = PrefUtils.getString("openId", "");
        isLoging = PrefUtils.getBoolean("isLogin", false);
        findViewById();

        if (initNetError()) {
            initDatas();
        }
    }

    private void initRecyclerview() {
        HomeAdapter homeAdapter = new HomeAdapter(result);
        homeAdapter.addHeaderView(headerView);
        GridLayoutManager manager = new GridLayoutManager(this, 2);
        rl.setLayoutManager(manager);
        rl.setAdapter(homeAdapter);
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(UiUtils.getContext(), CommodityActivity.class);
                intent.putExtra("text", result.get(position).D_title);//标题
                intent.putExtra("id", result.get(position).GoodsID);//商品id
                intent.putExtra("url", result.get(position).discountLink);//优惠卷连接
                intent.putExtra("pic", result.get(position).Pic);//图
                intent.putExtra("quan", result.get(position).Quan_receive);//已领券
                intent.putExtra("num", result.get(position).Sales_num);//购买数
                intent.putExtra("time", result.get(position).Quan_time);//过期时间
                intent.putExtra("quanPrice", result.get(position).Quan_price);//优惠卷金额
                intent.putExtra("orgPrice", result.get(position).Org_Price);//原价
                intent.putExtra("price", result.get(position).Price + "");//券后价
                intent.putExtra("cid", result.get(position).Cid + "");
                intent.putExtra("IsTmall", result.get(position).IsTmall);
                intent.putExtra("Commission", result.get(position).Commission_jihua);
                intent.putExtra("quanid", result.get(position).Quan_id);
                jumpToActivity(intent);
                finish();
            }
        });
        pro.setVisibility(View.GONE);
        ivShare.setClickable(true);
    }

    private void findViewById() {
        pic = (ImageView) headerView.findViewById(R.id.pic);
        tvText = (TextView) headerView.findViewById(R.id.tvText);
        tvMoney = (TextView) headerView.findViewById(R.id.tvMoney);
        oldMoney = (TextView) headerView.findViewById(R.id.oldMoney);
        sellNumber = (TextView) headerView.findViewById(R.id.sellNumber);
        youh = (TextView) headerView.findViewById(R.id.youh);
        quan = (TextView) headerView.findViewById(R.id.quan);
        tvQuan = (TextView) headerView.findViewById(R.id.tvQuan);
        tvBao = (TextView) headerView.findViewById(R.id.tvBao);
        tvTime = (TextView) headerView.findViewById(R.id.tvTime);
    }

    private void setMessage() {
        tvText.setText(text);
        tvMoney.setText(price);
        oldMoney.setText("原价" + orgPrice + "元");
        sellNumber.setText("销量" + saleNum + "件");
        quan.setText(priceNum);
        tvQuan.setText("已领取" + quanNum + "张");
        tvBao.setText("已有" + saleNum + "人购买");
        tvTime.setText("过期时间" + substring);
        Glide.with(this).asBitmap().load(picUrl).into(new BitmapImageViewTarget(pic) {
            @Override
            protected void setResource(Bitmap resource) {
                super.setResource(resource);
                setBitmap(resource);
            }
        });
    }

    private void setBitmap(Bitmap bitmap) {
        this.mBitmap = bitmap;
    }

    private void initDatas() {
        initData();
        initSimilarData();
        initShare();
    }

    //友盟分享
    private void initShare() {

        ivShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UiUtils.isNetworkAvailable()) {
                    UiUtils.toast("网络出问题了,请稍后重试!");
                    return;
                }
                //唤起分享界面
                showSharePop();
            }
        });
    }

    private void showSharePop() {
        View view = LayoutInflater.from(this).inflate(R.layout.share_pop_layout, null);
        LinearLayout llTao = (LinearLayout) view.findViewById(R.id.llTao);
        if (!IS_TAOKE) {
            llTao.setVisibility(View.GONE);
        }
        llTao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTaoWordDialog();
            }
        });

        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams
                .WRAP_CONTENT);
        popupWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        //        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(true);
        //设置可以点击
        popupWindow.setTouchable(true);
        //进入退出的动画
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        LinearLayout qq = (LinearLayout) view.findViewById(R.id.qq);
        LinearLayout zone = (LinearLayout) view.findViewById(R.id.zone);
        LinearLayout friend = (LinearLayout) view.findViewById(R.id.friend);
        LinearLayout wechat = (LinearLayout) view.findViewById(R.id.wechat);

        qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setShare(1);
            }
        });
        zone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setShare(2);
            }
        });
        wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setShare(3);
            }
        });
        friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setShare(4);
            }
        });

        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void setShare(int type) {
        popupWindow.dismiss();
        ShareUtil shareUtil = new ShareUtil(this, new BaseUiListener());
        if (mBitmap != null) {
            shareUtil.setType(type).setTitle("21特惠专属优惠券,赶快领取吧").setSummary(text).setUrl(shortLink)
                    .setImgUrl(picUrl).setImageBitmap(Bitmap.createScaledBitmap(mBitmap, 60, 60, true))
                    .creat();
        }
    }

    private class BaseUiListener implements IUiListener {
        @Override
        public void onComplete(Object response) {
        }

        @Override
        public void onError(UiError e) {
            UiUtils.toast("出现错误,请稍候再试");
        }

        @Override
        public void onCancel() {
        }
    }

    private void showTaoWordDialog() {
        final String body = "【天猫特惠】" + text + "\n【原价】" + orgPrice + "\n【券后价】" + price + "\n点击链接再选择浏览器打开" +
                shortLink + "\n或复制这条信息" + taoWord + "后打开手机淘宝\n【更多优惠请点击】" + downLink;
        Dialog dialog = new Dialog(this);
        View view = View.inflate(this, R.layout.tao_word_layout, null);
        Button btn = (Button) view.findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                copyBody(body);
            }
        });

        TextView taoBtn = (TextView) view.findViewById(R.id.taoWord);
        dialog.setContentView(view);
        taoBtn.setText(body);
        dialog.show();
    }

    private void copyBody(String body) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText(null, body));
        Toast.makeText(this, "复制成功", Toast.LENGTH_LONG).show();
    }

    //相似物品
    private void initSimilarData() {
        NR.getRequest(Global.URL_SIMILAR, this, new MyCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                //解析
                if (s.equals("-1")) {
                } else {
                    parseJson(s);
                }
            }
        });
    }

    //解析
    private void parseJson(String s) {
        BrandData brandData = JSON.parseObject(s, BrandData.class);
        result = brandData.result;
        initRecyclerview();
    }

    private void initData() {
        Intent intent = getIntent();
        boolean isFromFavorite = intent.getBooleanExtra("isFromFavorite", false);
        boolean isRollView = intent.getBooleanExtra("isRollView", false);
        if (isFromFavorite) {
            if (isRollView) {
            } else {
                ivFavorite.setImageResource(R.drawable.collect_ok);
                isChoice = true;
            }
            goodsId = intent.getStringExtra("goodsId");
            //请求网络
            getServre(goodsId);

        } else {
            picUrl = intent.getStringExtra("pic");
            text = intent.getStringExtra("text");
            //            url = intent.getStringExtra("url");
            goodsId = intent.getStringExtra("id");
            cid = intent.getStringExtra("cid");
            //已领券
            quanNum = intent.getStringExtra("quan");
            //购买数
            saleNum = intent.getStringExtra("num");
            //过期时间
            substring = intent.getStringExtra("time").substring(0, 10);
            //优惠卷金额;
            priceNum = intent.getStringExtra("quanPrice");
            //原价
            orgPrice = intent.getStringExtra("orgPrice");
            //券后价
            price = intent.getStringExtra("price");
            //是否天猫
            isTmall = intent.getStringExtra("IsTmall");
            commission = intent.getStringExtra("Commission");
            quanid = intent.getStringExtra("quanid");

            setMessage();
            //获取淘口令
            getTaoWord();
            upServreMessage();
            isFavorite();
        }
    }

    public void getServre(final String goodsIds) {

        NR.getRequest(Global.URL_DETAILS + goodsIds, this, new MyCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (s != null) {
                    parseFavoriteJson(s, goodsIds);
                }
            }
        });
    }

    private void parseFavoriteJson(String s, String goodsIds) {
        DanData brandData = JSON.parseObject(s, DanData.class);
        DanData.ResultBean result = brandData.result;
        if (result == null) {
            llBtn.setVisibility(View.GONE);
            invalid.setVisibility(View.VISIBLE);
            deleteFavorite(goodsIds);
            return;
        }

        picUrl = result.Pic;
        text = result.D_title;
        goodsId = result.GoodsID;
        cid = result.Cid;
        //已领券
        quanNum = result.Quan_receive;
        //购买数
        saleNum = result.Sales_num;
        //过期时间
        substring = result.Quan_time.substring(0, 10);
        //优惠卷金额;
        String prices = result.Quan_price;
        priceNum = prices.substring(0, prices.indexOf("."));
        //原价
        orgPrice = result.Org_Price;
        //券后价
        price = result.Price + "";
        commission = result.Commission_jihua;
        isTmall = result.IsTmall;
        quanid = result.Quan_id;
        setMessage();
        //获取淘口令
        getTaoWord();
        upServreMessage();
        isFavorite();
    }

    public void isFavorite() {
        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("OpenId", openId);
            jsonObject.put("Price", price);
            jsonObject.put("GoodsId", goodsId);
            jsonObject.put("Title", text);
            jsonObject.put("IsTmall", isTmall);
            jsonObject.put("TaokeId", taokeId);
            jsonObject.put("Commission", commission);
            String s = jsonObject.toString();
            NR.postRequest(Global.URL_ISFAVORITE, "str", s, this, new MyCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    //上传成功
                    try {
                        JSONObject jsonObject1 = new JSONObject(s);
                        String info = (String) jsonObject1.get("info");
                        if (info.equals("1")) {
                            if (isLoging) {
                                ivFavorite.setImageResource(R.drawable.collect_ok);
                                isChoice = true;
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void deleteFavorite(String goodsIds) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("GoodsId", goodsIds);//商品id
            jsonObject.put("OpenId", openId);//用户id
            String s = jsonObject.toString();
            NR.postRequest(Global.URL_DELETE_FAVORITE, "str", s, this, new MyCallback());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void deleteFavorite() {
        NR.postRequest(Global.URL_DELETE_FAVORITE, "str", sendFavorite, this, new MyCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                //上传成功
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    String info = (String) jsonObject.get("info");
                    if (info.equals("1")) {
                        UiUtils.toast("取消收藏成功");
                        ivFavorite.setImageResource(R.drawable.collect);
                        isChoice = false;
                    } else if (info.equals("-1")) {
                        isChoice = true;
                        UiUtils.toast("取消收藏失败");
                        ivFavorite.setImageResource(R.drawable.collect_ok);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private boolean initNetError() {
        if (!UiUtils.isNetworkAvailable()) {

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    rl.setVisibility(View.GONE);
                    llBtn.setVisibility(View.GONE);
                    llNet.setVisibility(View.VISIBLE);
                    pro.setVisibility(View.GONE);
                }
            }, 1000);

            return false;
        } else {
            return true;
        }
    }

    private void upServreMessage() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("Title", text);//标题
            jsonObject.put("GoodsId", goodsId);//商品id
            jsonObject.put("OpenId", openId);//用户id
            jsonObject.put("PicUrl", picUrl);//图片地址
            jsonObject.put("QuanPrice", priceNum);//优惠券金额
            jsonObject.put("SaleNum", saleNum);//销量
            jsonObject.put("Price", price);
            sendFavorite = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getTaoWord() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("goodsId", goodsId);
            jsonObject.put("activityId", quanid);
            jsonObject.put("pid", pid);
            jsonObject.put("taokeId", taokeId);
            String s = jsonObject.toString();
            NR.postRequest("http://dl.21tehui.com/AppGetTaoWordApi.html", "word", s, this, new MyCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    try {
                        JSONObject jsonObject1 = new JSONObject(s);
                        taoWord = jsonObject1.getString("taoWord");
                        shortLink = jsonObject1.getString("shortLink") + pid;

//                        alibcPage = new AlibcPage(shortLink);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.btn, R.id.rlFavorite})
    public void onClick(View view) {
        if (!UiUtils.isNetworkAvailable()) {
            UiUtils.toast("网络出问题了,请稍后重试!");
            return;
        }
        boolean isLogin = PrefUtils.getBoolean("isLogin", false);
        switch (view.getId()) {
            case R.id.btn:
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("TaokeId", taokeId);
                    jsonObject.put("OpenId", openId);
                    jsonObject.put("GoodsId", goodsId);
                    String s = jsonObject.toString();
                    NR.postRequest("http://dl.21tehui.com/Favorite/addSkip.html", "skip", s, this, new
                            MyCallback());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                exParams = new HashMap<>();
                exParams.put("isv_code", "appisvcode");
                exParams.put("alibaba", "阿里巴巴");//自定义参数部分，可任意增删改
                alibcShowParams = new AlibcShowParams(OpenType.Native, false);
                AlibcTrade.show(this, alibcPage, alibcShowParams, null, exParams, new AlibcTradeCallback() {
                    @Override
                    public void onTradeSuccess(TradeResult tradeResult) {
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Logger.d(i + "---" + s);
                    }
                });
                break;
            case R.id.rlFavorite:
                if (!isLogin) {
                    UiUtils.toast("请您先登录!");
                    jumpToActivity(LoginActivity.class);
                    return;
                }

                if (TextUtils.isEmpty(openId)) {
                    UiUtils.toast("登录已过期,请您去重新登录!");
                    PrefUtils.setBoolean("isLogin", false);
                    return;
                }

                if (!UiUtils.isNetworkAvailable()) {
                    UiUtils.toast("网络出问题了,请稍候重试!");
                    return;
                }
                if (isChoice) {
                    deleteFavorite();
                } else {
                    initFavorite();
                }
                break;
        }
    }

    private void initFavorite() {
        NR.postRequest(Global.URL_FAVORITE, "str", sendFavorite, this, new MyCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    String info = (String) jsonObject.get("info");
                    if (info.equals("1")) {
                        UiUtils.toast("收藏成功");
                        ivFavorite.setImageResource(R.drawable.collect_ok);
                        isChoice = true;
                    } else if (info.equals("-1")) {
                        isChoice = false;
                        UiUtils.toast("收藏失败");
                        ivFavorite.setImageResource(R.drawable.collect);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        AlibcTradeSDK.destory();
        super.onDestroy();
    }
}
